const logkey = 'xone-loc'
// https://lbs.qq.com/service/webService/webServiceGuide/webServiceGcoder
let key = 'KAIBZ-5XNCX-2WB4Y-ZVK7U-ZEKY3-UZFEI'
let baseUrl = 'https://apis.map.qq.com/ws/geocoder/v1'

let locationInfo
let loadinng = false

// #ifdef XT_PC
window.navigator.geolocation.getCurrentPosition=function(successCallback, errorCallback,PositionOptions) {
  PositionOptions = PositionOptions || {}
  PositionOptions.timeout = 3000
  return window.navigator.geolocation.getCurrentPosition(successCallback, errorCallback,PositionOptions)
}
// #endif

export function initLocation({refresh,poi,city, longitude,latitude,save=true}={}) {
  // console.log('xone-location: initLocation:', refresh,poi,city, longitude,latitude)
  locationInfo = locationInfo||uni.getStorageSync('xone-location-data')
  // console.log('xone-location: locationInfo:', locationInfo)
  if(locationInfo&&!refresh) {
    return Promise.resolve(locationInfo)
  }else if(city){
    loadinng = true
    return getLocationByCity(city).then(res=>{
      let ret = res&&res[0]&&res[0][0]&&res[0][0].location
      if(!ret) return Promise.reject('无效城市')
      return geocoderLocation(ret.lng, ret.lat, poi).then(ress=>{
        ress.longitude = ret.longitude
        ress.latitude = ret.latitude
        return save?setLocation(ress):ress
      }).finally(()=>{
        loadinng = false
      })
    })
  }else if(longitude&&latitude){
    loadinng = true
    return geocoderLocation(longitude, latitude, poi).then(ress=>{
      ress.longitude = longitude
      ress.latitude = latitude
      return save?setLocation(ress):ress
    }).finally(()=>{
      loadinng = false
    })
  }else{
    if(loadinng) return new Promise(resolve=>{
      uni.$once('xone-location-data', res=>{
        resolve(res)
      })
    })
    loadinng = true
    return getLocation(poi).then(res=>{
      return save?setLocation(res):res
    }).finally(()=>{
      loadinng = false
    })
  }
}
export function chooseLocation(refresh) {
  return initLocation({refresh: true, poi: false, save: false}).then(res=>{
    return uni.chooseLocation({
      latitude: res.latitude,
      longitude: res.longitude,
    }).then(([err, res])=>{
      if(err) return Promise.reject()
      return res
    })
  })
}
export function setLocation(data) {
  locationInfo = data
  uni.setStorageSync('xone-location-data', locationInfo)
  uni.$emit('xone-location-data', locationInfo)
  return locationInfo
}

export function clearSelectedLocation() {
  locationInfo.selectdLocation = null
  uni.setStorageSync('xone-location-data', locationInfo)
  uni.$emit('xone-location-data', locationInfo)
}
export function setSelectedLocation(location) {
  locationInfo = location
  uni.setStorageSync('xone-location-data', locationInfo)
  uni.$emit('xone-location-data', locationInfo)
}
export function getSelectedLocation() {
  let ret = {
    longitude: locationInfo.longitude||0,
    latitude: locationInfo.latitude||0,
    title: locationInfo.formatted_addresses&&locationInfo.formatted_addresses.recommend||'',
    address: locationInfo.address||'' ,
    nation: locationInfo.address_component&&locationInfo.address_component.nation||'',
    province: locationInfo.address_component&&locationInfo.address_component.province||'',
    city: locationInfo.address_component&&locationInfo.address_component.city||'',
    district: locationInfo.address_component&&locationInfo.address_component.district||'',
    street: locationInfo.address_component&&locationInfo.address_component.street||'',
    nationCode: locationInfo.ad_info&&locationInfo.ad_info.nation_code||'',
    cityCode: locationInfo.ad_info&&locationInfo.ad_info.city_code||'',
    adcode: locationInfo.ad_info&&locationInfo.ad_info.adcode||'',
  }
  if(locationInfo.selectdLocation) {
    return {...ret, ...locationInfo.selectdLocation}
  }else{
    return ret
  }
}

export function geocoderLocation(longitude, latitude, poi) {
  return uni.$x.request.request({
    url: '/',
    baseUrl,
    isAuth: false,
    params: {
      key,
      location: `${latitude},${longitude}`,
      get_poi: poi?1:0
    }
  }).then(res=>{
    if(res.status!==0) return Promise.reject(res.status)
    return res.result
  })
}

export function getLocation(poi) {
  // console.log('xone-location: getLocation', poi)
  return uni.getLocation({
    // type: 'gcj02',
    type: 'wgs84'
  }).then(([err, res])=>{
    // console.log('uni.getLocation:', err, res)
    let longitude = 123.43, latitude = 41.8
    if(!err) {
      longitude = res.longitude
      latitude = res.latitude
    }
   
    if(poi) {
      return geocoderLocation(longitude, latitude, poi).then(ress=>{
        ress.longitude = longitude
        ress.latitude = latitude
        console.log('xone-location: getLocation ret', ress)
        return ress
      }).catch(e=>{
        console.log('xone-location: getLocation geocoder err', e)
        return {latitude,longitude}
      })
    }else{
      console.log('xone-location: getLocation ret', res)
      return res // {latitude,longitude}
    }
  })
}
// https://apis.map.qq.com/ws/geocoder/v1/location?key=KAIBZ-5XNCX-2WB4Y-ZVK7U-ZEKY3-UZFEI&location=41.71482,123.44972&get_poi=1
// https://apis.map.qq.com/ws/geocoder/v1/?location=39.984154,116.307490&key=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77&get_poi=1
export function geocoderSearch(keyword,longitude,latitude,radius=1000,auto_extend=true) {
  return uni.$x.request.request({
    url: '/search',
    baseUrl: 'https://apis.map.qq.com/ws/place/v1',
    isAuth: false,
    params: {
      key,
      keyword,
      boundary: `nearby(${latitude},${longitude},${radius},${auto_extend?1:0})`
    }
  }).then(res=>{
    if(res.status!==0) return Promise.reject(res.status)
    return res.data
  })
}
export function getLocationByCity(keyword) {
  return uni.$x.request.request({
    url: '/search',
    baseUrl: 'https://apis.map.qq.com/ws/district/v1',
    isAuth: false,
    params: {
      key,
      keyword,
    }
  }).then(res=>{
    if(res.status!==0) return Promise.reject(res.status)
    return res.result
  })
}
export function geocoderSuggestion() {
  
}